package beautiful.butterfly.drds.data_exchange.statistics.container.collector;


import beautiful.butterfly.drds.data_exchange.constant.Constants;
import beautiful.butterfly.drds.data_exchange.enums.State;
import beautiful.butterfly.drds.data_exchange.statistics.communication.Communication;
import beautiful.butterfly.drds.data_exchange.statistics.communication.LocalTGCommunicationManager;
import beautiful.butterfly.drds.data_exchange.util.Configuration;
import lombok.Getter;
import lombok.Setter;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class AbstractCollector
{
    private Map<Integer, Communication> taskCommunicationMap = new ConcurrentHashMap<Integer, Communication>();
    @Setter
    @Getter
    private Long jobId;

    public Map<Integer, Communication> getTaskCommunicationMap()
    {
        return taskCommunicationMap;
    }


    public void registerTGCommunication(List<Configuration> taskGroupConfigurationList)
    {
        for (Configuration config : taskGroupConfigurationList)
        {
            int taskGroupId = config.getInt(
                    Constants.container_taskgroup_id);
            LocalTGCommunicationManager.registerTaskGroupCommunication(taskGroupId, new Communication());
        }
    }

    public void registerTaskCommunication(List<Configuration> taskConfigurationList)
    {
        for (Configuration taskConfig : taskConfigurationList)
        {
            int taskId = taskConfig.getInt(Constants.task_id);
            this.taskCommunicationMap.put(taskId, new Communication());
        }
    }

    public Communication collectFromTask()
    {
        Communication communication = new Communication();
        communication.setState(State.succeeded);

        for (Communication taskCommunication :
                this.taskCommunicationMap.values())
        {
            communication.mergeFrom(taskCommunication);
        }

        return communication;
    }

    public abstract Communication collectFromTaskGroup();

    public Map<Integer, Communication> getTGCommunicationMap()
    {
        return LocalTGCommunicationManager.getTaskGroupCommunicationMap();
    }

    public Communication getTGCommunication(Integer taskGroupId)
    {
        return LocalTGCommunicationManager.getTaskGroupCommunication(taskGroupId);
    }

    public Communication getTaskCommunication(Integer taskId)
    {
        return this.taskCommunicationMap.get(taskId);
    }
}
